package com.wwwarehouse.resource_center.fragment.rules;

import android.app.Dialog;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.bean.rules.AllocationConditionBean;
import com.wwwarehouse.resource_center.bean.rules.OperatorTypeBean;
import com.wwwarehouse.resource_center.bean.rules.StocksBean;
import com.wwwarehouse.resource_center.bean.rules.TaskDetailedRule;
import com.wwwarehouse.resource_center.bean.rules.TaskUnitBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.RulesEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Joseph on 2017/8/9.
 *         <p/>
 *         新增保存规则,设置规则功能卡
 */
@Route(path = ResourceConstant.NEW_RULES)
public class SetRulesFragment extends TheParentFragment implements View.OnClickListener, DialogTools.ConfirmListener {

    protected RecyclerView mRecyclerView;
    protected RuleAdapter mAdapter;
    protected boolean iScanScroll = true;
    protected int mCount;
    protected View mTextRuleName;
    protected View mTextObject;
    protected View mTask;
    protected View mOperator;
    protected View mDistributionMode;
    protected ElasticScrollView mRuleScroll;
    public static final int QUERY_TASK_ALLOCATION_RULE = 2; //查询详细规则
    public static final int ADD_TASK_ALLOCATION_RULE = 3;  //新增
    public static final int DELETE_TASK_ALLOCATION_RULE = 4;  //删除
    public static final int UPDATE_TASK_ALLOCATION_RULE = 5;  //编辑
    public static final int QUERY_TASK_ALLOCATION_RULEALL = 6;  //所有规则详情
    public static final int GET_DISTRIBUT_ABLE_STOCKS = 7;  //获取未分配的应用对象
    protected ImageView imageobject;
    protected TextView tvobject;
    protected ImageView imagetask;
    protected TextView tvtask;
    protected ImageView imgoperator;
    protected TextView tvoperator;
    protected ImageView imgallocation;
    protected TextView tvallocation;
    protected String taskAllocationUkid;
    protected TextView ruleName;
    protected ArrayList<String> taskTypes = new ArrayList<>();
    protected ArrayList<String> StockesTypes = new ArrayList<>();
    protected String mRuleName;
    protected String valueCode = "yes_work";
    protected String valueName;
    protected String allocateTactics;
    protected String maxTaskNum;
    protected String operatorType = "HUMAN";
    protected String operatorName;
    protected String conditionCode = "is_work";
    protected List<Number> businessIds;
    protected List<StocksBean.ListBean> stockList;
    protected String businessId = "";
    protected ArrayList<String>  applyBusinessList ;  //应用对象
    private ArrayList<String> businessIdList = new ArrayList<>();//业务单位集合
    protected String ruleTitle ;
    protected int total; //应用对象个数
    protected ArrayList<StocksBean.ListBean> mStocksListBean = new ArrayList<>();  //应用对象
    protected ArrayList<TaskUnitBean.DataBean.ListBean> mTasksListBean = new ArrayList<>();//任务
    protected String allocateTacticsName;

    @Override
    protected int getContentId() {
        return R.layout.fragment_rule_save;
    }


    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void init(View view) {
        ruleName = findView(view, R.id.rule_name);
        mRecyclerView = findView(view, R.id.recy_sava_rule);
        mTextRuleName = findView(view, R.id.rl_rule_name);
        mTask = findView(view, R.id.rl_task);
        mTextObject = findView(view, R.id.rl_rule_object);
        mOperator = findView(view, R.id.rl_operator);
        mDistributionMode = findView(view, R.id.rl_allocation);
        mRuleScroll = findView(view, R.id.rule_scroll);
        this.tvallocation = (TextView) view.findViewById(R.id.tv_allocation);
        this.imgallocation = (ImageView) view.findViewById(R.id.img_allocation);
        this.tvoperator = (TextView) view.findViewById(R.id.tv_operator);
        this.imgoperator = (ImageView) view.findViewById(R.id.img_operator);
        this.tvtask = (TextView) view.findViewById(R.id.tv_task);
        this.imagetask = (ImageView) view.findViewById(R.id.image_task);
        this.tvobject = (TextView) view.findViewById(R.id.tv_object);
        this.imageobject = (ImageView) view.findViewById(R.id.rule_image_object);
    }

    @Override
    protected void loadDatas() {
        Bundle bundle = getArguments();
        if (null != bundle) {
            CardDeskFunctionResponseBean.TaskBean taskBean = (CardDeskFunctionResponseBean.TaskBean) bundle.getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
            if (taskBean != null) {
                businessId = taskBean.getBusinessId();
            } else {
                businessId = bundle.getString("businessId");
            }
            businessIdList.add(businessId);
        }
        ruleTitle  = getString(R.string.new_rule_name);
        mTextRuleName.setOnClickListener(this);
        mTextObject.setOnClickListener(this);
        mTask.setOnClickListener(this);
        mOperator.setOnClickListener(null);
        mDistributionMode.setOnClickListener(this);
        mRuleScroll.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                if (isShow) {
                    //显示按钮
                    ((BaseCardDeskActivity) mActivity).showTitleBt1();
                    ((BaseCardDeskActivity) mActivity).setTitleBt1Text(getString(R.string.button_text_save));
                } else {
                    //隐藏按钮
                    ((BaseCardDeskActivity) mActivity).hideTitleBt();
                }
                isShow = !isShow;
            }

            @Override
            public void onUpPull() {

            }
        });
    }

    @Override
    public void titleBt1Click() {
        if (peekFragment() instanceof SetRulesFragment) {
            ((BaseCardDeskActivity) mActivity).hideTitleBt();
            isShow = true;
            DialogTools.getInstance().showCustomDialogPrompt(mActivity, null, getString(R.string.resource_dialog_update), true, new DialogTools.ConfirmListener() {
                @Override
                public void setConfirmListener(Dialog dialog, View view, String input) {
                    addTaskAllocationRule();
                    dialog.dismiss();
                }
            }, "确定", "不了");
        }
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof SetRulesFragment)
            mActivity.setTitle(getString(R.string.add_set_rules_name));
    }

    @Override
    public void requestDatas() {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> baseQueryMap = new HashMap<>();
        baseQueryMap.put("page", 1);
        baseQueryMap.put("size", 1);
        baseQueryMap.put("sort", "UPDATE_TIME DESC");
        map.put("businessIdList",businessIdList );
        map.put("baseQuery", baseQueryMap);
        httpPost(ResourceConstant.GET_DISTRIBUT_ABLE_STOCKS, map, GET_DISTRIBUT_ABLE_STOCKS, true, "");

//        int min = 1;
//        int max = 5;
//        Random random = new Random();
//        mCount = random.nextInt(max) % (max - min + 1) + min;
//        //设置布局管理器
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity) {
//            @Override
//            public boolean canScrollHorizontally() {
//                return false;
//            }
//        };
//        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        mRecyclerView.setLayoutManager(linearLayoutManager);
//        mAdapter = new RuleAdapter();
//        mRecyclerView.addItemDecoration(new SpaceItemDecoration(ConvertUtils.dip2px(mActivity,5)));
//        mRecyclerView.setAdapter(mAdapter);
    }

    //保存
    protected void addTaskAllocationRule() {
        Map<String, Object> obj = new HashMap<>();
        obj.put("applyBusinessList", StockesTypes);
        obj.put("businessId", businessId);
        Map<String, Object> cfTaskAllocate = new HashMap<>();
        cfTaskAllocate.put("allocateTactics", allocateTactics);
        cfTaskAllocate.put("maxTaskNum", maxTaskNum);
        cfTaskAllocate.put("ruleName", mRuleName);
        obj.put("cfTaskAllocate", cfTaskAllocate);
        ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("conditionCode", conditionCode);
        conditions.put("valueCode", valueCode);
        arrayList.add(conditions);
        obj.put("conditions", arrayList);
        obj.put("operatorType", operatorType);
        obj.put("taskTypes", taskTypes);
        httpPost(ResourceConstant.ADD_TASK_ALLOCATION_RULE, obj, ADD_TASK_ALLOCATION_RULE, true, "请求中……");
    }

    //删除
    protected void deleteTaskAllocationRule() {
        Map<String, Object> obj = new HashMap<>();
        obj.put("businessId", businessId);
        obj.put("taskAllocateUkid", taskAllocationUkid);
        httpPost(ResourceConstant.DELETE_TASK_ALLOCATION_RULE, obj, DELETE_TASK_ALLOCATION_RULE, true, "");
    }
    @Override
    public void onClick(View v) {
        ((BaseCardDeskActivity) mActivity).hideTitleBt();
        isShow = true;
        int i = v.getId();
        if (i == R.id.rl_rule_name) {
            SetRuleNameFragment fragment = new SetRuleNameFragment();
            Bundle  bundle = new Bundle() ;
            bundle.putString("mRuleName",mRuleName);
            bundle.putString("RuleTitle",ruleTitle);
            bundle.putString("businessId",businessId);
            fragment.setArguments(bundle);
            pushFragment(fragment);

        } else if (i == R.id.rl_rule_object) {
            //应用对象
            SelectObjectFragment fragment = new SelectObjectFragment();
            Bundle  bundle = new Bundle();
            bundle.putString("businessId",businessId);
            bundle.putInt("total",total);
            bundle.putParcelableArrayList("mStocksListBean", mStocksListBean);
            fragment.setArguments(bundle);
            pushFragment(fragment);

        } else if (i == R.id.rl_task) {
            //任务
            SelectTaskParentFragment fragment = new SelectTaskParentFragment();
            Bundle  bundle = new Bundle();
            bundle.putString("businessId",businessId);
            bundle.putParcelableArrayList("mSelectTasksListBean",  mTasksListBean);
            fragment.setArguments(bundle);
            pushFragment(fragment);

        } else if (i == R.id.rl_operator) {
//            pushFragment(new SelectOperatorFragment());

        } else if (i == R.id.rl_allocation) {
            SetDistributionModeFragment fragment = new SetDistributionModeFragment();
            Bundle  bundle = new Bundle();
            OperatorTypeBean type  = new OperatorTypeBean();
            type.setCode(allocateTactics);
            type.setName(allocateTacticsName);
            type.setMaxTaskNum(maxTaskNum);
            bundle.putParcelable("data",type);
            fragment.setArguments(bundle);
            pushFragment(fragment);

        }
    }

    public void onEventMainThread(RulesEvent event) {
        switch (event.getCode()) {
            case RulesEvent.RULE_NAME:
                if (event.getMsg().equals("RULE_NAME")) {
                    ruleName.setText((String) event.getData());
                    mRuleName = (String) event.getData();
                }
                break;
            case RulesEvent.RULE_BUSINESSIDS:


                break;
            case RulesEvent.RULE_TASK:
                if (event.getMsg().equals("RULE_TASK")) {
                    //任务
                    mTasksListBean = new ArrayList<>();
                    ArrayList<TaskUnitBean.DataBean.ListBean>  listBeen = (ArrayList<TaskUnitBean.DataBean.ListBean>) event.getData();
                    mTasksListBean.addAll(listBeen);
                    setTask(mTasksListBean);
                }  else if (event.getMsg().equals("RULE_STOCKS")) {
                    //应用对象
                    mStocksListBean = new ArrayList<>();
                    ArrayList<StocksBean.ListBean> dataList = (ArrayList<StocksBean.ListBean>)event.getData();
                    mStocksListBean.addAll(dataList);
                    setStock(mStocksListBean);
                }
                break;
            case RulesEvent.RULE_OPERATOR:
                Map<String, Object> objectMap = (Map<String, Object>) event.getData();
                ArrayList<AllocationConditionBean> conditionBeen = (ArrayList<AllocationConditionBean>) objectMap.get("conditions");
                ArrayList<OperatorTypeBean> typeBeen = (ArrayList<OperatorTypeBean>) objectMap.get("typeBeen");
                if (typeBeen != null) {
                    for (int i = 0; i < typeBeen.size(); i++) {
                        if (typeBeen.get(i).isSelect()) {
                            operatorType = typeBeen.get(i).getCode();
                            operatorName = typeBeen.get(i).getName();
                            break;
                        }
                    }
                }
                if (conditionBeen != null) {
                    for (int i = 0; i < conditionBeen.size(); i++) {
                        List<AllocationConditionBean.ConditionValuesBean> conditionValues = conditionBeen.get(i).getConditionValues();
                        conditionCode = conditionBeen.get(i).getConditionCode();
                        for (int i1 = 0; i1 < conditionValues.size(); i1++) {
                            if (conditionValues.get(i1).isSelect()) {
                                valueCode = conditionValues.get(i1).getValueCode();
                                valueName = conditionValues.get(i1).getValueName();
                                break;
                            }
                        }
                    }
                }
                LogUtils.showInfoLog("operatorType:" + operatorType + "operatorName:" + operatorName);
                tvoperator.setText(operatorName + "、" + valueName);

                break;
            case RulesEvent.RULE_ALLOCATETACTICS:
                OperatorTypeBean type = (OperatorTypeBean) event.getData();
                allocateTactics = type.getCode();
                maxTaskNum = event.getMsg();
                allocateTacticsName = type.getName();
                tvallocation.setText(allocateTacticsName + "、" + "饱和度<" + maxTaskNum);
                break;
        }
    }

    public  void setStock(List<StocksBean.ListBean> listBeen) {
        StockesTypes = new ArrayList<>();
        StringBuffer   task = new StringBuffer();
        for (int i = 0; i < listBeen.size(); i++) {
            if (i == listBeen.size() - 1) {
                task.append(listBeen.get(i).getStockName());
            } else {
                task.append(listBeen.get(i).getStockName() + "、");
            }
            StockesTypes.add(listBeen.get(i).getStockUkid());
        }
        if (task.length() > 0) {
            tvobject.setText(task);
        }
    }

    public void setTask(List<TaskUnitBean.DataBean.ListBean> selectDatas) {
        taskTypes.clear();
        StringBuffer task = new StringBuffer();
        for (int i = 0; i < selectDatas.size(); i++) {
            if (i == selectDatas.size() - 1) {
                task.append(selectDatas.get(i).getAcitonUnitName());
            } else {
                task.append(selectDatas.get(i).getAcitonUnitName() + "、");
            }
            taskTypes.add(selectDatas.get(i).getAcitonUnitType());
        }
        if (task.length() > 0) {
            tvtask.setText(task);
        }
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        switch (what) {
            case GET_DISTRIBUT_ABLE_STOCKS:  //获取未分配的应用对象
                if (TextUtils.equals("0", commonClass.getCode())) {
                    StocksBean stocksBean = JSON.parseObject(commonClass.getData().toString(), StocksBean.class);
                    stockList = stocksBean.getList();
                    if (stockList != null && stockList.size() > 0) {
                        ChangeState();
                        total = stocksBean.getTotal();
                        applyBusinessList = new ArrayList<>();
                        for (int i1 = 0; i1 < stockList.size(); i1++) {
                            applyBusinessList.add(stockList.get(i1).getStockUkid());
                        }
                    } else {
                        DialogTools.getInstance().showCustomWarning(mActivity, "无法新建", "由于没有应用对象可供选择,所以你当前无法新建任何任务分配规则", "好的", false, new DialogTools.OnDismissListener() {
                            @Override
                            public void setDismissListener(Dialog dialog, View view) {
                                popFragment();
                            }
                        }, null);
                    }
                } else {
                    DialogTools.getInstance().showCustomWarning(mActivity, "无法新建", "由于没有应用对象可供选择,所以你当前无法新建任何任务分配规则", "好的", false, new DialogTools.OnDismissListener() {
                        @Override
                        public void setDismissListener(Dialog dialog, View view) {
                            popFragment();
                        }
                    }, null);
                }
                break;
            case ADD_TASK_ALLOCATION_RULE:  //新增
                if (TextUtils.equals("0", commonClass.getCode())) {
                    popFragment();
                    ConfigurationSuccessFragment successFragment = new ConfigurationSuccessFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("success", "success");
                    bundle.putString("businessId", businessId);
                    successFragment.setArguments(bundle);
                    pushFragment(successFragment);
                } else if (TextUtils.equals("60010", commonClass.getCode())){
                    DialogTools.getInstance().showCustomWarning(mActivity, getString(R.string.dialog_1_title), commonClass.getMsg(), false, new DialogTools.ConfirmListener() {
                        @Override
                        public void setConfirmListener(Dialog dialog, View view, String input) {
                            dialog.dismiss();
                            //任务
                            SelectTaskParentFragment fragment = new SelectTaskParentFragment();
                            Bundle  bundle = new Bundle();
                            bundle.putString("businessId",businessId);
                            bundle.putParcelableArrayList("mSelectTasksListBean",  mTasksListBean);
                            fragment.setArguments(bundle);
                            pushFragment(fragment);
                        }
                    });
                }
                else {
                    DialogTools.getInstance().showCustomWarning(mActivity, "提示", commonClass.getMsg(), "我知道了", false, SetRulesFragment.this);
                }
                break;
            case QUERY_TASK_ALLOCATION_RULE:

                if (TextUtils.equals("0", commonClass.getCode())) {
                    TaskDetailedRule rule = JSON.parseObject(commonClass.getData().toString(), TaskDetailedRule.class);
                    ruleName.setText(rule.getRuleName());
//                        businessIds = rule.getBusinessIds();
                    StringBuffer bId = new StringBuffer();
                    for (int i = 0; i < businessIds.size(); i++) {
                        if (i == businessIds.size() - 1) {
                            bId.append(businessIds.get(i));
                        } else {
                            bId.append(businessIds.get(i) + "、");
                        }
                    }
                    if (bId.length() > 0) {
                        tvobject.setText(bId);
                    }
                    List<TaskDetailedRule.TaskTypesBean> taskTypes = rule.getTaskTypes();
                    StringBuffer taskType = new StringBuffer();
                    for (int i = 0; i < taskTypes.size(); i++) {
                        if (i == taskTypes.size() - 1) {
//                                taskType.append(taskTypes.get(i).getTaskTag());
                        } else {
//                                taskType.append(taskTypes.get(i).getTaskTag()+"、");
                        }
                    }
                    tvtask.setText(taskType);
                    List<TaskDetailedRule.RulesBean> rules = rule.getRules();
                    StringBuffer rul = new StringBuffer();
                    for (int i = 0; i < rules.size(); i++) {
                        if (rules.get(i).getOperator() != null) {
                            rul.append(rules.get(i).getOperator() + "、" + rules.get(i).getItemCode() + "\\n");
                        }
                    }
                    if (rul.length() > 0) {
                        tvoperator.setText(rul);
                    }
                    tvallocation.setText(rule.getAllocateTactics() + "、" + "饱和度<" + rule.getTaskMaxNum());
                }


                break;
            case DELETE_TASK_ALLOCATION_RULE:


                break;
            case UPDATE_TASK_ALLOCATION_RULE:

                break;
            case QUERY_TASK_ALLOCATION_RULEALL: //业务单位对应所有规则详情(信息卡片) TaskDetailedRule
                ArrayList<TaskDetailedRule> desks = (ArrayList<TaskDetailedRule>) JSON.parseArray(commonClass.getData().toString(), TaskDetailedRule.class);


                break;
        }
    }

    /**
     * 改变背景颜色，图标，字体颜色
     */
    private void ChangeState() {
        mTextObject.setBackgroundColor(getResources().getColor(R.color.common_color_c12_836fdb));
        mTask.setBackgroundColor(getResources().getColor(R.color.common_color_c1_337cff));
//        mOperator.setBackgroundColor(getResources().getColor(R.color.common_color_c13_23c0b1));
        mDistributionMode.setBackgroundColor(getResources().getColor(R.color.common_color_c13_23c0b1));
        tvobject.setTextColor(getResources().getColor(R.color.common_color_c3_ffffff));
        tvtask.setTextColor(getResources().getColor(R.color.common_color_c3_ffffff));
        tvallocation.setTextColor(getResources().getColor(R.color.common_color_c3_ffffff));
//        tvoperator.setTextColor(getResources().getColor(R.color.common_color_c3_ffffff));
        imageobject.setImageResource(R.drawable.resource_object_icon_object);
        imagetask.setImageResource(R.drawable.icon_task);
//        imgoperator.setImageResource(R.drawable.icon_operator);
        imgallocation.setImageResource(R.drawable.icon_allocation);
    }

    @Override
    public void onReLoad(int code) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ((BaseCardDeskActivity) mActivity).hideTitleBt();
    }

    @Override
    public void setConfirmListener(Dialog dialog, View view, String input) {
        dialog.dismiss();
    }

    class RuleAdapter extends RecyclerView.Adapter<RuleAdapter.ViewHolder> {

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(View arg0) {
                super(arg0);
            }

            ImageView mImag;
            TextView mTxtTaskName;
            TextView mTxtNumber;

        }

        @Override
        public int getItemCount() {
            return mCount;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.rule_task_item, viewGroup, false);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
            //获取当前控件的布局对象
            params.width = (mRecyclerView.getWidth() - (getItemCount() - 1) * ConvertUtils.dip2px(mActivity, 5)) / getItemCount();//设置当前控件布局的宽度和margin
            view.setLayoutParams(params);//将设置好的布局参数应用到控件中
            ViewHolder viewHolder = new ViewHolder(view);
            viewHolder.mTxtTaskName = (TextView) view
                    .findViewById(R.id.task_name);
            viewHolder.mTxtNumber = (TextView) view
                    .findViewById(R.id.task_num);
            viewHolder.mImag = (ImageView) view
                    .findViewById(R.id.task_img);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    startActivityForResult(SelectTaskActivity.class,SELECT_TASK,new Bundle());
                }
            });
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
            viewHolder.mTxtTaskName.setText("退货");
            viewHolder.mTxtNumber.setText("退货点数");

        }
    }

    class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        int mSpace;

        @Override

        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

            super.getItemOffsets(outRect, view, parent, state);

//                outRect.left = mSpace;
//
//                outRect.right = mSpace;
//
//                outRect.bottom = mSpace;

            if (parent.getChildAdapterPosition(view) != 0) {
                outRect.left = mSpace;
            }
        }

        public SpaceItemDecoration(int space) {
            this.mSpace = space;
        }
    }

    class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            if (iScanScroll)
                if (Math.abs(distanceY) >= Math.abs(distanceX))
                    iScanScroll = true;
                else
                    iScanScroll = false;

            if (iScanScroll) {
                if (e1.getAction() == MotionEvent.ACTION_DOWN) {
//                    moveYY = 0;
//                    startY = e1.getY();
                }
            }
            return iScanScroll;
        }
    }
}
